import webp from "@cwasm/webp";
import { fileTypeFromBuffer } from "file-type";
import jpeg from "jpeg-js";
import { PNG } from "pngjs";

import { blockhash } from "./block-hash.js";

function processPNG(buffer, bits) {
  const png = PNG.sync.read(buffer);
  return blockhash(png, bits, 2);
}

function processJPG(buffer, bits) {
  const decoded = jpeg.decode(buffer);
  return blockhash(decoded, bits, 2);
}

function processWebp(data, bits) {
  const decoded = webp.decode(data);
  return blockhash(decoded, bits, 2);
}

/**
 * @description
 *
 *
 * @param {Buffer} buffer
 * @returns {Promise<string>}
 */
export async function imageHash(buffer) {
  if (!Buffer.isBuffer(buffer)) throw new Error(`Invalid args buffer`);

  const { mime, ext } = await fileTypeFromBuffer(buffer);
  const bits = 16;

  if (mime === "image/png") {
    return processPNG(buffer, bits);
  } else if (mime === "image/jpeg") {
    return processJPG(buffer, bits);
  } else if (mime === "image/webp") {
    return processWebp(buffer, bits);
  } else {
    throw new Error(`Unrecognized mime type: ${mimetype}`);
  }
}
